package myapps.ttclient.cryptography;

import java.util.ArrayList;

public class ExponentialEncryptFunction {
	public static int ExponentalEncryt(int message, int key, int prime){
		if (message >= prime){
			return -1;
		}
		int digest = 0;
		BigInteger keyBigInt = BigIntegerManager.ConvertToBase_2(key);
		digest = keyBigInt.ExponentMod_Base2(message, prime);
		return digest;
	}
}

class BigInteger{
	private byte NumericBase = 2;
	
	private ArrayList<Byte> binary = new ArrayList<Byte>();
	
	public BigInteger(){
		
	}
	
	public BigInteger(byte numericBase, ArrayList<Byte> binary){
		this.NumericBase = numericBase;
		this.binary.addAll(binary);
	}
	
	//em = x ^ this (mod m)
    public int ExponentMod_Base2(int x, int m)
    {
        int em = -1;
        if (this.NumericBase == 2)
        {
            em = 1;
            if (this.IsZero())
                return em;
            int a = x;
            if (this.binary.get(0) == 1)
                em = x;
            for (int i = 1; i < this.binary.size(); i++)
            {
                a = (a * a) % m;
                if (this.binary.get(i) == 1)
                    em = (a * em) % m;
            }
        }
        return em;
    }
    
    private boolean IsZero(){
    	for (int i = 0; i < this.binary.size(); i++){
    		if (this.binary.get(i) != 0)
    			return false;
    	}
    	return true;
    }
}

class BigIntegerManager{
	public static BigInteger ConvertToBase_2(int m){
		ArrayList<Byte> temp = new ArrayList<Byte>();
		int n = (int)(Math.log10(m) / Math.log10(2));
		for (int i = n; i >= 1; i--){
			Byte k = (byte) (m / (int)Math.pow(2, i));
			temp.add(k);
			m -= k * (int)Math.pow(2, i);
		}
		temp.add((byte)m);
		for (int i = 0; i < temp.size() / 2; i++){
			Byte t = temp.get(i);
			temp.set(i, temp.get(temp.size() - 1 - i));
			temp.set(temp.size() - 1 - i, t);
			
		}
		
		BigInteger bigInt = new BigInteger((byte)2, temp);
		return bigInt;
	}
}